<template>
  <div class="my-cropper">
    <div class="handle-mask" v-if="imageUrl">
      <div class="handle-btns">
        <div class="handle-icon" @click="handlePictureCardPreview">
          <i class="el-icon-zoom-in"></i>
        </div>
        <div class="handle-icon" v-if="!disabled" @click="handleRemove">
          <i class="el-icon-delete-solid"></i>
        </div>
      </div>
    </div>
    <el-upload
      class="upload-demo"
      ref="upload"
      :action="$http.adornUrl('/admin/file/upload/img/path')"
      :headers="{
        Authorization: $cookie.get('Authorization_vp'),
      }"
      list-type="picture-card"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="changeUpload"
      :disabled="disabled"
      :limit="limit"
    >
      <i class="el-icon-plus" v-if="!disabled"></i>

      <!-- 显示裁剪后的图片 -->
      <p class="file-image" v-if="imageUrl">
        <img :src="resourcesUrl + imageUrl" />
      </p>
    </el-upload>

    <!-- vueCropper 剪裁图片实现-->
    <el-dialog
      title="图片剪裁"
      :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="cropper-content">
        <div class="cropper" style="text-align: center">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :info="true"
            :canScale="option.canScale"
            :autoCrop="option.autoCrop"
            :autoCropWidth="option.autoCropWidth"
            :autoCropHeight="option.autoCropHeight"
            :fixedBox="option.fixedBox"
            :fixed="option.fixed"
            :fixedNumber="option.fixedNumber"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :original="option.original"
            :centerBox="option.centerBox"
            :infoTrue="option.infoTrue"
            :full="option.full"
            :enlarge="option.enlarge"
            :mode="option.mode"
            @imgLoad="imgLoad"
          >
          </vueCropper>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <div>
          <el-button
            style="margin-left: 15px"
            size="mini"
            @click="$refs.cropper.clearCrop()"
            >清除截图</el-button
          >
          <el-button size="mini" @click="$refs.cropper.goAutoCrop()"
            >开启截图</el-button
          >
          <el-button size="mini" @click="imgRotate('rotateLeft')"
            >左旋转</el-button
          >
          <el-button size="mini" @click="imgRotate('rotateRight')"
            >右旋转</el-button
          >
        </div>

        <div>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="finish" :loading="loading"
            >确认</el-button
          >
        </div>
      </div>
    </el-dialog>

    <el-dialog
      title="查看"
      width="60%"
      style="z-index: 999999"
      append-to-body
      :visible.sync="showImgDialog"
    >
      <div class="box">
        <img class="show-img" :src="resourcesUrl + imageUrl" alt="" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 使用vue-cropper 图片上传组件
import { VueCropper } from "vue-cropper";
// https://github.com/xyxiao001/vue-cropper

import { uploadFile } from "@/utils/httpRequest.js";

export default {
  components: {
    VueCropper,
  },
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    disabled: {
      default: false,
      type: Boolean,
    },
    onlyUsePush: {
      default: false,
      type: Boolean,
    },
    limit: {
      default: 1,
      type: Number,
    },
    // 宽高
    width: {
      default: "200px",
      type: String,
    },
    height: {
      default: "200px",
      type: String,
    },
    cropW: {
      default: "200",
      type: String,
    },
    cropH: {
      default: "200",
      type: String,
    },
    options: {
      type: Object || null,
      default: null,
    },
  },
  data() {
    return {
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      imageUrl: "",
      dialogVisible: false,
      showImgDialog: false,
      // 裁剪组件的基础配置option
      option: {
        img: "", // 裁剪图片的地址
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: "png", // 裁剪生成图片的格式
        info: true, // 裁剪框的大小信息
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        // autoCropWidth: 200, // 默认生成截图框宽度
        // autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [200, 200], // 截图框的宽高比例
        canMove: true, // 上传图片是否可以移动
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: true, // 截图框是否被限制在图片里面
        infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
        full: true, // 是否输出原图比例的截图
        enlarge: "0.1", // 图片根据截图框输出比例倍数
        mode: "contain", // 图片默认渲染方式
      },
      // 防止重复提交
      loading: false,
    };
  },

  watch: {
    modelValue: function (val) {
      if (val) {
        this.imageUrl = val;
      } else {
        this.imageUrl = "";
      }
    },
    dialogVisible: function (val) {
      if (val) {
        this.loading = false;
      }
    },
  },
  mounted() {
    if (this.modelValue) {
      this.imageUrl = this.modelValue;
    }
    this.option.fixedNumber = [this.cropW, this.cropH];
    if (this.cropW && this.cropH) {
      this.option.autoCropWidth = this.cropW;
      this.option.autoCropHeight = this.cropH;
    }
    if (this.options) {
      this.option = {
        ...this.option,
        ...this.options,
      };
    }
  },
  methods: {
    handleRemove() {
      this.imageUrl = "";
      this.$emit("update:modelValue", "");
      this.$emit("input", "");
    },
    handlePictureCardPreview() {
      this.showImgDialog = true;
    },
    imgLoad() {},
    imgRotate(fn) {
      this.$refs.cropper[fn]();
      this.$refs.cropper.goAutoCrop();
    },
    // 上传按钮 限制图片大小
    changeUpload(file, fileList) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error("上传文件大小不能超过 5MB!");
        this.$refs.upload.clearFiles();
        return false;
      }
      // 上传成功后将图片地址赋值给裁剪框显示图片
      this.$nextTick(() => {
        this.option._fileName = file.name;
        this.option.img = URL.createObjectURL(file.raw);
        this.dialogVisible = true;
        this.$refs.upload.clearFiles();
      });
    },
    // 裁剪处理后的地址
    finish() {
      this.$refs.cropper.getCropBlob((blob) => {
        this.loading = true;
        let file = this.blobToFile(blob);
        uploadFile(
          this.$http.adornUrl("/admin/file/upload/img/path"),
          file
        ).then(({ data }) => {
          if (data.data) {
            if (!this.onlyUsePush) {
              this.imageUrl = data.data;
            }
            this.$message.success("上传成功");
            setTimeout(() => {
              this.loading = false;
            }, 300);
            this.dialogVisible = false;
            this.$emit("update:modelValue", data.data);
            this.$emit("input", data.data);
          }
        });
      });
    },
    blobToFile(blob) {
      return new File([blob], this.option._fileName);
    },
  },
};
</script>

<style lang="scss" scoped>
.my-cropper {
  width: max-content;
  position: relative;
  display: flex;
}
.file-image {
  position: absolute;
  left: 0;
  top: 0;
  width: 100% !important;
  height: 100% !important;
  pointer-events: none;
  padding: 0;
  margin: 0;
  img {
    width: 100% !important;
    height: 100% !important;
    object-fit: contain;
  }
}

.cropper {
  width: 80vw;
  height: 60vh;
}
::v-deep .el-dialog {
  width: max-content !important;
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
}

.my-cropper:hover .handle-mask {
  opacity: 1;
  transition: opacity 0.3s linear;
}

.handle-mask {
  position: absolute;
  border-radius: 8px;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.4);
  z-index: 3;
  opacity: 0;
}
.handle-btns {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 60%;
  height: max-content;
  margin: auto;
  display: flex;
  justify-content: space-around;
  color: white;
  font-size: 28px;
}
.handle-icon {
  cursor: pointer;
}
.box {
  min-width: 600px;
  min-height: 300px;
  display: flex;
  align-items: center;
}
.show-img {
  max-width: 50vw;
  margin: 0 auto;
  width: max-content;
  display: block;
}
</style>
